//app打包时,测试环境使用此地址
//var reqUrl = 'http://licaishi.superfa.cn';

//app打包时,正式环境使用此地址
// var reqUrl = 'http://m.jincs.cn';

var reqUrl = '';

var domainname,isuseoss,citeImgUrl, VIDEO_CLIENT_ID, ACAPPID, calbackUrl, ACSTATE, ISWEB,ISONLINE,APITYPE;

if (reqUrl.indexOf("m.jincs.cn") > -1 || window.location.href.indexOf("m.jincs.cn") > -1) {//生产环境
    //分享图片---使用产品图片---pImageUrl---，使用http://lec.superfa.cn域名。
    //APP里获取的href为本地地址，无法做动态判断--
    citeImgUrl = 'http://lec.superfa.cn';//share 线上地址
    //优酷视频应用ID
    VIDEO_CLIENT_ID = 'f8f3c7ce0d32de2d';//生产
    //微信授权APPID
    ACAPPID = 'wx39c5948cd034acf5';//金策师
    //ACAPPID = 'wxf16851cfae7174ae';//正气
    //微信授权回调地址
    calbackUrl = 'm.jincs.cn';
    ACSTATE = '89';//生产
    //CHAT_APPKEY = 'm7ua80gbmp1cm';
    CHAT_APPKEY = 'm7ua80gbmwn1m';
    //线上还是测试环境变量
    ISONLINE = true;
    //普通引用地址
    domainname = 'm.jincs.cn';
    isuseoss = '0';//是否使用oss 0：是 1：否--线上使用OSS
    APITYPE = 'jincs';//API-接口请求类别，如，wap和jincs
} else {
    citeImgUrl = 'http://140.143.133.124';
    // citeImgUrl = 'http://m.jincs.cn';
    VIDEO_CLIENT_ID = '075a56369d668464';//测试
    // ACAPPID = 'wxad1ea380284b2b48';//正气
    ACAPPID = 'wx1cd6f8becf45e145';//正气
    // ACAPPID = 'wx39c5948cd034acf5';//金策师
    // calbackUrl = 'm.superfa.cn';
    calbackUrl = '140.143.133.124';
    ACSTATE = '88';//测试
    //CHAT_APPKEY = 'kj7swf8okhe82';
    CHAT_APPKEY = 'vnroth0kv4f3o';
    ISONLINE = false;
    domainname = '140.143.133.124';
    isuseoss = '1';//是否使用oss 0：是 1：否--线上使用
    APITYPE = 'jincs';//API-接口请求类别，如，wap和jincs
}
//判断是否为H5环境
if(!reqUrl) {
    ISWEB = true;//H5
} else {
    ISWEB = false;
}
//上传接口url
var fileUploadUrl = '/'+APITYPE+'/api/fileUpload?fileType=faUserCert';
//图片地址--如头像
var baseHref = reqUrl;
var isOpenLogin = false;
//优酷视频播放密码--
var VIDEO_PWD;
//版本号--
var version = '?'+Math.random() ;
//微讲堂接口前缀
var WXJKQZ = reqUrl + '/wx/webapi';

//这里声明一下为何不使用angular server 的cookies
//需求是需要在在每一个http请求上带上服务器的token
//这就必须写在angular config上，而server的注入是在此之后的
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

/**
 * Base64加解密封装
 *
 * @constructor
 */
function Base64() {

    // private property
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }

    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }

    // private method for UTF-8 encoding
    _utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    }

    // private method for UTF-8 decoding
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

// 对象键值对法去重
function unique2(array) {
    var n = {}, r = [], len = array.length, val, type;
    for (var i = 0; i < array.length; i++) {
        val = array[i];
        type = typeof val;
        if (!n[val]) {
            n[val] = [type];
            r.push(val);
        } else if (n[val].indexOf(type) < 0) {
            n[val].push(type);
            r.push(val);
        }
    }
    return r;
}
String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}

// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.map', 'starter.cookie', 'starter.core', 'starter.filter', 'starter.productCtrl', 'starter.myself', 'starter.controllers', 'starter.counselor', 'starter.shop', 'starter.activity','starter.pay'])

    .run(function ($faUtil, $faModal, $ionicPopup, $location, $chatToken, $faAPI, $faMAP, $ionicPlatform, $faPlatform, $rootScope, $ionicHistory, $state, $faUser, $timeout, $ionicConfig, $interval, $faPopup) {
        if(ISONLINE){
            //生产使用
            $rootScope.baseUrl = "http://m.jincs.cn";
            $rootScope.staticBaseUrl = "https://static-superfa-cn.alikunlun.com";
        }else {
            //测试使用
            $rootScope.baseUrl = "http://140.143.133.124";
            $rootScope.staticBaseUrl = "http://140.143.133.124";
        }
        //初始化
        //$rootScope.isNewsCome = false;//消息-红点通知
        //$rootScope.isCusvisit = false;//客户-红点通知
        //$rootScope.isHaveShopnews = false;//消息通知-红点通知
        $rootScope.isNetworkOk = true;//网络链接状态 true:链接中 false：已断开
        $rootScope.isInPrompt = true;//是否在网络断开页面 true:是 false:否
        $rootScope.isInLoginHtml = false;//是否在登录页
        $rootScope.isshowac = true;//是否显示广告

        $rootScope.jincs_env = APITYPE;

        $rootScope.goShophome = function(){
            $state.go('shopHome')
        }

        //统计 - 按钮及页面埋点统计
        /**
         *
         * @param type 编号类型
         * @param url  跳转路由
         * @param shopId 店主手机号
         * @param userId 用户mobile
         * @param parm 路由跳转所带参数
         */
        $rootScope.count_statis_btnAndPage = function(type, url, shopId, userId,parm){
            console.info($location.path());

            //跳转
            if(parm != null) {
                $state.go(url, eval('(' + parm + ')'));
            } else {
                $state.go(url);
            }

            var reqData = {
                type: type,
                host: $location.host(),
                path: $location.path(),
                param: $location.search(),
                source: 'WAP',
                shopId: shopId,
                userId: userId

            };
            $faAPI.shops.statis({
                type: 'statisitics',
                data: reqData
            }).then(function (json) {
            });
        }

        //拨打电话
        $rootScope.bodaPhone =function() {
            if ($faPlatform.IOSAPP) {
                //IOS拨打电话
                phonedialer.dial("02131038770", function (err) {
                    if (err == "feature")
                        console.info("Your device doesn't support this feature.");
                    if (err == "empty")
                        console.info("Unknown phone number");
                });
            } else {
                //ANDROID拨打电话
                window.location.href = "tel:02131038770";
            }
        }
        $rootScope.toPhone =function(phone) {
            if ($faPlatform.IOSAPP) {
                //IOS拨打电话
                phonedialer.dial(phone, function (err) {
                    if (err == "feature")
                        console.info("Your device doesn't support this feature.");
                    if (err == "empty")
                        console.info("Unknown phone number");
                });
            } else {
                //ANDROID拨打电话
                window.location.href = "tel:"+phone;
            }
        }

        //$rootScope.baseUrl = "http://127.0.0.1:2209";
        //通过ua判断新老版本，提示用户升级
        //var ua = window.navigator.userAgent;
        //
        //if(ua.match(/superfa/i)){
        //  $ionicPopup.alert({
        //    title:'金策师APP已经发布新版本，如继续使用旧版本，部分功能将不可使用，请至App Store搜索“金策师”升级，体验最新版本',
        //    okText:'知道了'
        //  });
        //}

        // if (window.location.href.indexOf('inviteHome') < 0) {
        //     //加载全局认证状态
        //     //为了在未登录的情况下拿到认证状态。
        //     $faUser.getInfo();
        // }


        $rootScope.event = {};
        $rootScope.relation = {};
        //用于全局跨控制器引用地址前缀
        $rootScope.requrl = reqUrl;
        //用来控制nav-bar上面分享app里面出现，h5不出现的问题
        //判断环境的状态，到不了nav上面，待解决
        $rootScope.ISWEB = ISWEB;
        $rootScope.contrastData = {};
        //产品对比数据存储
        function isContrastData() {
            var _data = $faUtil.localStorage('contrastData');

            //var length = Object.keys(_data).length;
            if (_data) {
                $rootScope.contrastData = _data;
            } else {
                $rootScope.contrastData = {};
            }
            //console.log($rootScope.contrastData);
        }

        isContrastData();
        //获取融云token,初始APP融云登录
        function getryToken() {
            $faAPI.shops.ryToken().then(function (data) {
                //console.log('getrytoken');
                //console.log(data);
                $chatToken.setter(data.token);
                $chatToken.setter_img(data.portraitUri);
                if (!ISWEB) {
                    //初始化
                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        if ($faPlatform.IOSAPP) {
                            var ry = 0;
                            var rytimer = $interval(function(){
                                if(ry==1) {
                                    $interval.cancel(rytimer);
                                    return;
                                }
                                try{
                                    if(ry==0) {
                                        loginRongyun(data.token);
                                    }
                                    ry = 1;
                                }catch(e) {
                                    ry = 0;
                                    console.info('异常');
                                }
                            },500);
                            //loginRongyun(data.token);

                        } else if ($faPlatform.androidAPP){
                            console.log('loginRongyun');
                            document.addEventListener("deviceready", OnDeviceReady, false);
                            function OnDeviceReady() {
                                cordova.exec(null, null, "MyPlugin", "loginRongyun", [data.token]);
                            }
                        }

                    }

                    var userInfo = {
                        appKey: CHAT_APPKEY,
                        token: data.token
                    };

                    // initRongyun(userInfo)
                }
            });
        }

        // if($faUtil.localStorage.get('user') && $faUtil.localStorage.get('user').isLogin) {
        //     getryToken();
        // }

        //私募投资管理法说明
        $faModal('law', 'views/modals/law.html', $rootScope, {
            done: function () {
                //$faAPI.user.addUserAgreeAgreement({
                //  fpFaLoginName:$rootScope.loginSuccessName,
                //  fpAgreeAgreement:'1'
                //}).then(function(res){});
                this.hide();
                window.localStorage.isClickLaw = true;
                //新手引导
                //$rootScope.startGuidance1();
            }
        });

        //私募管理法过滤路由地址--2016/11/11暂时直接if判断
        //var fiterUrl = [
        //  '/allin','/inviteHome','/inside','/blindHome','/blindCommit'
        //];

        // indexOf() 如果要检索的字符串值没有出现，则该方法返回 -1。
        //判断是否同意过私募管理法
        //$timeout(function(){
        //  if(window.localStorage){
        //    //2016/11/11--add
        //    if(!window.localStorage.isClickLaw){
        //      var href = window.location.href;
        //      //if(href.indexOf('?')>0){//有参数为-1
        //
        //      //if(!window.localStorage.isClickLaw && (fiterUrl.indexOf(href.substring(href.indexOf('#')+1,href.indexOf('?'))))<0)
        //      if(href.indexOf('blindHome')<0 && href.indexOf('blindCommit')<0 && href.indexOf('inviteHome')<0 && href.indexOf('inside')<0&& href.indexOf('shoPreview')<0&& href.indexOf('app.shopsIndex'))
        //      {
        //        $rootScope.modal.law();
        //      }
        //
        //    }
        //
        //  }else {
        //    //不支持localStorage，默认弹出
        //    $rootScope.modal.law();
        //  }
        //},1000);
        //

        //全局由产品列表跳转详情方法
        $rootScope.toView = function (type, id) {

            if (type && id) {
                var url = '';

                if (type == '01') {
                    url = 'product.simu';
                    if (!$faUser.info.isLogin) {
                        $rootScope.modal.login();
                        return
                    }
                } else if (type == '02' || type == '03') {
                    url = 'product.xtzgdetail';
                } else if (type == '07') {
                    url = 'product.xtzgdetail';
                    if (!$faUser.info.isLogin) {
                        $rootScope.modal.login();
                        return
                    }
                }
                else if (type == '06') {
                    url = 'product.pevc';
                    if (!$faUser.info.isLogin) {
                        $rootScope.modal.login();
                        return
                    }
                }

                $state.go(url, {id: id});
            } else {
                console.log('error,,');
            }
            $rootScope.isHide = true;
        };

        $rootScope.goCertification = function ($event) {
            $event.stopPropagation();
            $faUser.info.isLogin ? $state.go('app.myself.certification') : $rootScope.modal.login();
        };


        /**
         * [register]
         */
        $faModal('register', 'views/common/register.html', $rootScope, {
            step: 1,
            interval: 60,
            time: (new Date()).getTime(),
            sendTimer: '',
            config: $ionicConfig,
            initialize: function () {
                var self = this;
                $faAPI.user.verifyCode().then(function(json){
                    console.log(json)
                    alert(1)

                })


                if (!($rootScope.login && $rootScope.login.modal)) {
                    $rootScope.relation.weChatBind = false;
                }
                self.data = {
                    _pt: 'wap',
                    agree: true,

                    actSource: $rootScope.actSource || 'SBD300',
                    mid: $rootScope.mid,
                    sourceMobile: $rootScope.srcID//2016/08/22--4.2需求/2016/11/08--恢复
                };

                self.interval = 0;
                self.step = 1;
                self.isShowPassword = false;

                self.uFrom = '1';//注册初始化用户来源

                self.randNum = Math.random();
                self.getRandNum = function () {
                    self.randNum = Math.random();
                }
            },

            reset: function () {
                this.time = (new Date()).getTime();
            },

            sendVcode: function () {
                var self = this;
                var _data = this.data;



                if (!self.data.mobile) {
                    $faPopup.alert({
                        title: '未填写手机号码'
                    });
                } else if (!/^1\d{10}$/.test(self.data.mobile)) {
                    $faPopup.alert({
                        title: ' 手机号码格式错误'
                    });
                }else if(!self.data.imgvCode){
                    $faPopup.alert({
                        title: '未填写图形验证码'
                    });
                } else {
                    $faAPI.user.verification({mobile:self.data.mobile}).then(function(res){
                        console.info(res)
                        if(res.statusCode == '0000'){
                            //console.info("执行")

                            $faAPI.media.sendLoginVcode({mobile: self.data.mobile, codeFlag: 'register',verifyCode:self.data.imgvCode}).then(function (resq) {
                                if(resq.AB) {
                                    $faPopup.alert({
                                        title: '短信请求过于频繁，请稍候再试！'
                                    });
                                } else {
                                    self.interval = 60;
                                    $interval.cancel(self.sendTimer);

                                    self.sendTimer = $interval(function () {
                                        if (self.interval > 0) {
                                            self.interval--;
                                        } else {
                                            $interval.cancel(self.sendTimer);
                                            self.interval = 0;
                                            self.randNum = Math.random();
                                        }
                                    }, 1000);
                                }
                            });
                        }else if(res.attributes.ufrom != '1' && res.statusCode == "2011"){
                            $faPopup.alert({
                                title: ' 已在金策师注册过了哦 <br/>可直接登录'
                            });
                        }else if(res.statusCode == "2011" && res.attributes.ufrom == '1'){
                            /* $faPopup.alert({
                             title: '手机号已被注册了哦'
                             });*/
                            $ionicPopup.confirm({
                                title: '手机号已被注册',
                                buttons: [{
                                    text: '重新填写',
                                    type: 'button-default'

                                }, {
                                    text: '去登录',
                                    type: 'button-positive confirmLogin',
                                    onTap: function(){
                                        self.hide()
                                    }

                                }]
                            })
                        }
                    })
                }
            },
                imgYzfun:function(){
                    $faAPI.user.verifyCode().then(function(json){
                        alert(1)
                    })
                },


            nextStep: function () {
                // var self = this;
                // if (!self.data.mobile) {
                //   $faPopup.alert({
                //     title: '未填写手机号码'
                //   });
                // } else if (!/^1\d{10}$/.test(self.data.mobile)) {
                //   $faPopup.alert({
                //     title: ' 手机号码格式错误'
                //   });
                // } else if (!self.data.verifyCode) {
                //   $faPopup.alert({
                //     title: '未填写验证码'
                //   });
                // } else {
                //   self.sendVcode();
                // }
            },
            showLogin: function () {
                var self = this;
                if ($rootScope.login && $rootScope.login.modal) {
                    self.hide();
                } else {
                    $rootScope.modal.login();
                }
            },
            done: function () {
                var self = this;

                if (!self.data.mobile) {
                    $faPopup.alert({
                        title: '未填写手机号码'
                    });
                } else if (!/^1\d{10}$/.test(self.data.mobile)) {
                    $faPopup.alert({
                        title: ' 手机号码格式错误'
                    });
                } else if(!self.data.imgvCode){
                    $faPopup.alert({
                        title: '未填写图形验证码'
                    });
                }  else if (!self.data.vCode) {
                    $faPopup.alert({
                        title: '未填写短信验证码'
                    });
                } else if (!self.data.password) {
                    $faPopup.alert({
                        title: '未填写登陆密码'
                    });
                } else if (!/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,18}$/.test(self.data.password)) {
                    $faPopup.alert({
                        title: '密码格式有误'
                    });
                } else {
                    var promise = $rootScope.relation.weChatBind ? $faAPI.wechat.register : $faAPI.user.register;
                    self.data.uFrom ='1'
                    promise(self.data).then(function (json) {
                        console.info(json)
                        /* $faUser.update();
                         $rootScope.modal.userAuth();*/

                        //$faUser.update();
                        //$faUtil.cookie('phoneid', json.phoneid, {
                        //    path: '/',
                        //    expires: 1296000
                        //});
                        //$faUtil.cookie('token', json.token, {
                        //    path: '/',
                        //    expires: 1296000
                        //});
                        self.hide();

                        if(json.statusCode=='2011') {
                            $faPopup.alert({
                                title: ' 已在金策师注册过了哦 <br/>可直接登录'
                            });
                        } else if(json.statusCode=='0000') {
                            $faUser.update();
                            $rootScope.modal.userAuth();

                            //$faUser.update();
                            //$faUtil.cookie('phoneid', json.phoneid, {
                            //    path: '/',
                            //    expires: 1296000
                            //});
                            //$faUtil.cookie('token', json.token, {
                            //    path: '/',
                            //    expires: 1296000
                            //});
                            self.hide();
                            getryToken();

                            window.localStorage.setItem("startpage", "seen");

                            //注册完成后调用极光推送设备注册ID接口
                            $faUser.info.isLogin = true;
                            window.plugins.jPushPlugin.getRegistrationID(onGetRegistrationID);

                            $faAPI.shops.shopUserInfo({
                                loginName: self.data.mobile
                            }).then(function (json) {
                                $rootScope.shopYxtAd = json.shopYxtAd;//英雄帖广告显示开关
                            });
                            $rootScope.pupclos = true;
                            $rootScope.isshowac = true;
                        }

                        //$rootScope.login && $rootScope.login.hide();
                        //$rootScope.loginSuccessName = self.data.mobile;
                        //$rootScope.modal.law();

                        //$state.go('app.myself.certification');

                    });
                }

            }
        });
        /**
         * [agreement]
         */
        $faModal('showXieyi', 'views/common/fastLoginXieyi.html', $rootScope);

        /**
         * [login]
         * mcallback--login success callback
         * create by yuanhui--2016/10/14
         */

        $faModal('login', 'views/common/login.html', $rootScope, {
            initialize: function () {
                $rootScope.loWidth = window.innerWidth;
                $rootScope.loHeight = window.innerHeight;
                // window.onload = function () {
                //
                // }
                var timer=$timeout(function(){
                    var login = document.getElementById('login');
                    //console.log(login)
                    var login1 = function () {

                        // if(!login.style) {
                        //     login.style = {};
                        // }
                        login.style.width =  $rootScope.loWidth +'px';
                        login.style.height = $rootScope.loHeight +'px';
                    }
                    login1()
                },300);

                var self = this;
                isOpenLogin = true;
                $rootScope.navShow = false;

                self.randNum = Math.random();
                self.getRandNum = function () {
                    self.randNum = Math.random();
                }

                $rootScope.relation.weChatBind = false;
                self.data = {
                    _pt: 'wap',
                    loginName: $faUser.info.mobile,
                    validatecode: ''
                };

                $rootScope.datasa = function(data){
                    console.log(data);
                }
                self.isShowPassword = true;

                $rootScope.userLoginModel = this;

                self.isFastLogin = false;//是否短信随机码登录

                self.interval = 0;//短信时效

                $rootScope.isInLoginHtml = true;//是否在登录页 true:在
            },

            sendVcode: function () {
                var self = this;
                var _data = this.data;
                if (!self.data.loginName) {
                    $faPopup.alert({
                        title: '未填写手机号码'
                    });
                } else if (!/^1\d{10}$/.test(self.data.loginName)) {
                    $faPopup.alert({
                        title: ' 手机号码格式错误'
                    });
                }else if(!self.data.imgvCode){
                    $faPopup.alert({
                        title: '未填写图形验证码'
                    });
                } else {
                    $faAPI.media.sendLoginVcode({mobile: self.data.loginName,verifyCode:self.data.imgvCode}).then(function (res) {
                        if(res.AB) {
                            $faPopup.alert({
                                title: '短信请求过于频繁，请稍候再试！'
                            });
                        } else {
                            self.interval = 60;
                            console.info("获取验证码")
                            $interval.cancel(self.sendTimer);

                            self.sendTimer = $interval(function () {
                                if (self.interval > 0) {
                                    self.interval--;
                                } else {
                                    $interval.cancel(self.sendTimer);
                                    self.interval = 0;
                                    self.randNum = Math.random();
                                }
                            }, 1000);
                        }
                    });
                }
            },

            pasCheck:function(){
                var self = this;
                $scope.isDis = !disabled;
                if(self.data.loginName >=6){
                    $scope.isDis = disabled;
                }
            },
            over: function () {
                var self = this;
                // if ($scope.register && $scope.register.modal) {
                //     $scope.register.hide();
                // }
            },

            showRegister: function () {
                var self = this;
                if ($rootScope.register && $rootScope.register.modal) {
                    self.hide();
                }   else {
                    $rootScope.modal.register();
                }
            },

            hide: function() {
                var self = this;
                self.over();
                if (self.modal) {
                    self.modal.remove().then(function () {
                        self.modal = null;
                    });
                }

                $rootScope.isInLoginHtml = false;//是否在登录页 false:否
            },

            showFastLogin: function () {
                var self = this;
                if ($rootScope.fastLogin && $rootScope.fastLogin.modal) {
                    self.hide();
                } else {
                    $rootScope.modal.fastLogin();
                }
            },

            hasProblem: function () {
                var self = this;
                $ionicActionSheet.show({
                    buttons: [{
                        text: '注册账号'
                    }, {
                        text: '重置密码'
                    }],
                    cancelText: '取消',
                    buttonClicked: function (index) {

                        if (index === 0) {

                            if ($rootScope.register && $rootScope.register.modal) {

                                self.modal.remove().then(function () {
                                    self.modal = null;
                                });

                            } else {
                                $rootScope.modal.register();
                            }

                        } else if (index === 1) {
                            $rootScope.modal.forgetPassword();
                        }

                        return true;
                    }
                });
            },
            update: function (json) {

                var self = this;

                $faUser.update(json);

                $faUtil.cookie('_token') && $faUtil.localStorage('_token', $faUtil.cookie('_token').replace(/\"/g, ''));

                self.hide();
            },
            done: function () {
                var self = this;

                if (!self.data.loginName) {
                    $faPopup.alert({
                        title: '请输入手机号码'
                    });
                } else if (!/^1\d{10}$/.test(self.data.loginName)) {
                    $faPopup.alert({
                        title: '手机号码格式错误'
                    });
                }  else if (!self.data.password) {
                    $faPopup.alert({
                        title: '未填写登陆密码'
                    });
                } else if (!/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,18}$/.test(self.data.password)) {
                    $faPopup.alert({
                        title: '密码格式有误'
                    });
                } else {

                    var promise = $rootScope.relation.weChatBind ? $faAPI.wechat.login : $faAPI.user.login;

                    promise(self.data).then(function (json) {
                        $rootScope.isshowac = true;//显示广告英雄会

                        //self.update(json);
                        console.log(json)
                        if(json.shopperUserInfoDto.userName) {
                            $rootScope.shopUserName = json.shopperUserInfoDto.userName;
                        } else {
                            $rootScope.shopUserName = json.uRealName
                        }
                        $rootScope.shopUserPhone = json.loginName;
                        $rootScope.shopUserImg = json.shopperUserInfoDto.userHeadImg;

                        if($rootScope.relation.weChatBind && !json.shopperUserInfoDto.userHeadImg) {
                            $rootScope.shopUserImg = json.uImage;//无店铺头像默认取微信头像
                        }

                        if ($faUser.info.isLogin) {

                            $faUser.info = $faUtil.extend($faUser.info, json);

                            $faUtil.localStorage('user', $faUser.info);

                            if (self.mcallback) {
                                self.mcallback()
                            }

                            if($location.path()=='/') {
                                $state.go('shopHome');//如果在启动页则直接跳转首页
                            }else {
                                self.hide();
                                $state.reload();
                            }

                        } else {
                            $faAPI.user.info().then(function(res) {
                                console.info(res)
                                if($faPlatform.IOSAPP||$faPlatform.androidAPP) {
                                    //重新注册极光推送设备
                                    window.plugins.jPushPlugin.getRegistrationID(onGetRegistrationID);
                                }

                                var _info = {};
                                //add-2016/5/6，全局认证状态--nomad-使用全局变量，退出销毁
                                //1.未提交认证，2.98认证中，3.99认证失败
                                $rootScope.userRole = res.user.uRole;
                                //$rootScope.userImage = res.user.uImage;

                                $rootScope.curUserRole = res.user.uRole;
                                if(res.user.uRole == 1 || res.user.uRole == 98 || res.user.uRole == 99){
                                    $rootScope.userRole = 'RZ';
                                }else {
                                    $rootScope.userRole = 'ZC';
                                }
                                //if(!res.user.flagVistProjectInfo){
                                //  $state.go('app.myself.certification');
                                //}


                                angular.forEach($faMAP.user, function(value, key) {

                                    _info['isLogin'] = true;

                                    if (key === 'name') {
                                        _info[key] = res.user.uRealName || (res.user.faUserWechatDTO ? res.user.faUserWechatDTO.nickname : undefined) || res.user.uLoginName;
                                    } else if (key === "avatar") {
                                        _info[key] = (res.user.faUserWechatDTO ? res.user.faUserWechatDTO.headimgurl : undefined) || res.user.uImage;
                                    } else if (key === "industry") {
                                        _info[key] = res.user.authenticationDTO ? res.user.authenticationDTO.trade : undefined;
                                    } else if (key === "working") {
                                        _info[key] = res.user.authenticationDTO ? res.user.authenticationDTO.tradeAge : undefined;
                                    } else {
                                        _info[key] = res.user[value];
                                    }

                                });

                                $faUser.update(_info);

                                if (self.mcallback) {
                                    self.mcallback()
                                }
                                self.hide();
                            }, function(res) {

                                if (res.statusCode === '2001') {
                                    $rootScope.userRole = 'DL';

                                    //up-nomad-2016-4-13--zanshi

                                    //直接跳转会引发第一次进个人，又退回来。--nomad.2016.04.14
                                    //$state.go('app');
                                }
                                self.hide();
                            });
                            $rootScope.isActive1 = true;
                        }

                        if($faPlatform.androidAPP) {
                            document.addEventListener("deviceready", OnDeviceReady, false);

                            function OnDeviceReady() {
                                cordova.exec(null, null, "MyPlugin", "setToken", [json.token, json.phoneid]);
                            }
                        }

                        $faUtil.cookie('phoneid', json.phoneid, {
                            path: '/',
                            expires: 1296000
                        });
                        $faUtil.cookie('token', json.token, {
                            path: '/',
                            expires: 1296000
                        });

                        //用来更新产品列表的登录或者认证状态
                        //if(window.isprolistUpdate){
                        //  window.isprolistUpdate();
                        //}
                        //用来更新课程详情
                        if (window.keCallback) {
                            window.keCallback();
                        }
                        //用来更新视频状态
                        //$rootScope.isUserLogin = '1';
                        try {
                            $rootScope.register.hide();
                        } catch (e) {

                        }

                        // 如果是ios或Android设备
                        //if ($faPlatform.androidAPP || $faPlatform.IOSAPP) {
                        //    $faAPI.user.userPhoneAlias({alias: $faPlatform.deviceAlias || ''}).then(function (json) {
                        //        //alert(JSON.stringify(json));
                        //        //console.log(json);
                        //    });
                        //}
                        //if(!json.flagVistProjectInfo){
                        //  $state.go('app.myself.certification');
                        //}
                        //刷新接口更改状态
                        getryToken();
                        $state.reload();
                    });

                }
            },
            fastdone: function () {
                var self = this;

                if (!self.data.loginName) {
                    $faPopup.alert({
                        title: '请输入手机号码'
                    });
                } else if (!/^1\d{10}$/.test(self.data.loginName)) {
                    $faPopup.alert({
                        title: '手机号码格式错误'
                    });
                } else if(!self.data.imgvCode){
                    $faPopup.alert({
                        title: '未填写图形验证码'
                    });
                } else if (!self.data.validatecode) {
                    $faPopup.alert({
                        title: '请输入手机验证码'
                    });
                } else {
                    $faAPI.user.quickLogin(self.data).then(function (json) {
                        $rootScope.isshowac = true;//显示广告英雄会
                        console.info(json)
                        json.isLogin = true;
                        json.mobile = json.loginName;

                        if(json.shopperUserInfoDto.userName) {
                            $rootScope.shopUserName = json.shopperUserInfoDto.userName;
                        } else {
                            $rootScope.shopUserName = json.uRealName
                        }
                        $rootScope.shopUserPhone = json.loginName;

                        self.update(json);
                        $faUtil.cookie('phoneid', json.phoneid, {
                            path: '/',
                            expires: 1296000
                        });
                        $faUtil.cookie('token', json.token, {
                            path: '/',
                            expires: 1296000
                        });
                        //用来更新视频状态
                        //$rootScope.isUserLogin = '1';
                        try {
                            //$rootScope.fastLogin.hide();
                            //$rootScope.startpage.hide();
                            window.localStorage.setItem("startpage", "seen");//隐藏引导页
                            //$rootScope.login.hide();

                            if($location.path()=='/') {
                                $state.go('shopHome');//如果在启动页则直接跳转首页
                            }else {
                                self.hide();
                                $state.reload();
                            }
                        } catch (e) {
                        }
                        getryToken();
                        //$state.reload();
                        //if(!json.flagVistProjectInfo){
                        //  $state.go('app.myself.certification');
                        //}


                    });
                }
            },
            weixin: function () {

                var self = this;

                $faIOSBridge.connect(function (bridge) {
                    bridge.send('wxLogin');
                });

            },
            androidWeixin: function () {
                // console.log('11');
                // alert('11');
                // alert(JSON.stringify(Wechat));

                //Wechat.setOptions({
                //    appId: 'wx36b7d36024a194bc'
                //});

                Wechat.isInstalled(function (installed) {
                    if(!installed){
                        $faPopup.alert({
                            title: '您还未安装微信！'
                        });
                        return;
                    }

                    Wechat.auth("snsapi_userinfo", "_" + (+new Date()), function (response) {

                        $faAPI.wechat.appback(response).then(function (json) {

                            if (!!$rootScope.modal.login) {
                                json.isLogin = true;
                                json.mobile = json.loginName;

                                $rootScope.login.update(json);
                                $faUser.info = {//登录成功
                                    isLogin: true
                                };

                                //店铺用户名称 > 上传认证 > 微信名称
                                if(json.shopperUserInfoDto.userName) {
                                    $rootScope.shopUserName = json.shopperUserInfoDto.userName;
                                } else {
                                    //if(json.userName) {
                                    $rootScope.shopUserName = json.uRealName;
                                    //} else {
                                    //    $rootScope.shopUserName = json.faUserWechatDTO.nickname;
                                    //}
                                }
                                $rootScope.shopUserPhone = json.loginName;
                                $rootScope.shopUserImg = json.faUserWechatDTO.headimgurl;

                                window.localStorage.setItem("startpage", "seen");//隐藏引导页

                                try {
                                    $faUtil.cookie('phoneid', json.phoneid, {
                                        path: '/',
                                        expires: 1296000
                                    });
                                    $faUtil.cookie('token', json.token, {
                                        path: '/',
                                        expires: 1296000
                                    });
                                } catch (err) {
                                }
                                getryToken();

                                //查询用户信息
                                if($location.path()=='/') {
                                    $state.go('shopHome');//如果在启动页则直接跳转首页
                                }else {
                                    $state.reload();
                                }

                            }
                        }, function (json) {
                            //2016/08/22需求直接关联
                            $rootScope.relation.weChatBind = true;

                        });

                    }, function (reason) {
                        //if (reason == 'ERR_USER_CANCEL') {
                        //  $faPopup.alert({
                        //    title: '已取消'
                        //  });
                        //}
                        //} else {
                        //  $faPopup.alert({
                        //    title: reason
                        //  });
                        //}
                    });
                });
                //屏蔽用户取消后的提示
                //}, function (reason) {
                //  $faPopup.alert({
                //    title: reason
                //  });
                //});

            }
        });

        /**
         * 用户认证
         */
        $faModal('userAuth', 'views/common/userAuth.html', $rootScope, {
            initialize: function() {
                var self = this;
                self.data = {};

                self.data.uSex = '1';//默认男
            },
            gotoCustomer:function(){
                this.hide();
                if($rootScope.userLoginModel) {
                    $rootScope.userLoginModel.hide();
                }
                $state.go('customer')

            },
            cropPhotoShopUserAuth: function() {
                var self = this;

                if(!self.data) {
                    self.data = {};
                }

                //1用户头像/2店铺头像/3店铺背景
                try {
                    if (!ISWEB) {
                        if ($faPlatform.IOSAPP) {
                            cropPhoto('userAuthImg');
                        }

                        if ($faPlatform.androidAPP) {

                            document.addEventListener("deviceready", OnDeviceReady, false);
                            function OnDeviceReady() {
                                cordova.exec(null, null, "MyPlugin", "cropPhoto", ['userAuthImg']);
                            }

                        }
                    }
                } catch(e) {
                    alert(e)
                }

                window.userAuthImg = function (url) {
                    //alert(url)
                    self.data.uCardAddress = url;
                    $rootScope.$apply()
                };
            },
            goshHome: function() {
                this.hide();
                if($rootScope.userLoginModel) {
                    $rootScope.userLoginModel.hide();
                }
                $state.go('shopHome')
            },
            done: function () {

                var self = this;

                if(!self.data.uRealName) {
                    $faPopup.alert({
                        title: '请填写真实姓名'
                    });
                } else if(!self.data.uSex){
                    $faPopup.alert({
                        title: '请选择性别'
                    });
                } else if(!self.data.uCardType){
                    $faPopup.alert({
                        title: '请选择资料认证类型'
                    });
                } else if(!self.data.uCardAddress){
                    $faPopup.alert({
                        title: '请上传认证资料图片'
                    });
                } else {

                    self.data.uFrom = '1';
                    self.data.uRole = '98';
                    $faAPI.shops.userAuth(self.data).then(function (json) {
                        //console.info(json)
                        //if(json.statusCode=='0000') {
                        //    $ionicPopup.alert({
                        //        title: '提交成功！',
                        //        buttons: [{
                        //            'text': '确定',
                        //            'type': 'button-positive'
                        //        }]
                        //    }).then(function () {
                        //        window.location.reload();
                        //    })
                        if($rootScope.userLoginModel) {
                            $rootScope.userLoginModel.hide();
                        }

                        console.info("路由："+$location.path())
                        if($location.path() == '/shopHome'){
                            $faUser.update();
                            // $state.reload();
                        } else {
                            $state.go('shopHome');
                        }

                        self.hide();
                        //}
                    });
                }
            }
        })

        /**
         * [forget password]
         */
        $faModal('forgetPassword', 'views/common/forget.html', $rootScope, {
            step: 1,
            interval: 60,
            time: (new Date()).getTime(),
            sendTimer: '',





            initialize: function () {
                var self = this;

                $interval.cancel(self.sendTimer);

                self.data = {
                    _pt: 'wap',
                    agree: true
                };

                self.interval = 0;
                self.step = 1;
                self.isShowPassword = false;
                self.title = '忘记密码';

                self.randNum = Math.random();
                self.getRandNum = function () {
                    self.randNum = Math.random();
                }

            },
            showLogin: function () {
                var self = this;
                if ($scope.login && $scope.login.modal) {
                    self.hide();
                }
                $rootScope.modal.login();
            },
            reset: function () {
                this.time = (new Date()).getTime();
            },
            sendVcode: function () {
                var self = this;
                var _data = this.data;
                if (!self.data.mobile) {
                    $faPopup.alert({
                        title: '未填写手机号码'
                    });
                } else if (!/^1\d{10}$/.test(self.data.mobile)) {
                    $faPopup.alert({
                        title: ' 手机号码格式错误'
                    });
                }else if(!self.data.imgvCode){
                    $faPopup.alert({
                        title: '未填写图形验证码'
                    });
                } else {


                    _data.codeFlag = 'forgetPasswd';
                    _data.verifyCode = self.data.imgvCode;
                    $faAPI.media.sendLoginVcode(_data).then(function (resq) {
                        if(resq.AB) {
                            $faPopup.alert({
                                title: '短信请求过于频繁，请稍候再试！'
                            });
                        } else {
                            self.interval = 60;
                            $interval.cancel(self.sendTimer);

                            self.sendTimer = $interval(function () {
                                if (self.interval > 0) {
                                    self.interval--;
                                } else {
                                    $interval.cancel(self.sendTimer);
                                    self.interval = 0;
                                    self.randNum = Math.random();
                                }
                            }, 1000);
                        }
                    });
                }
            },
            nextStep: function () {
                var self = this;
                if (!self.data.mobile) {
                    $faPopup.alert({
                        title: '未填写手机号码'
                    });
                } else if (!/^1\d{10}$/.test(self.data.mobile)) {
                    $faPopup.alert({
                        title: ' 手机号码格式错误'
                    });
                } else if(!self.data.imgvCode){
                    $faPopup.alert({
                        title: '未填写图形验证码'
                    });
                }  else if (!self.data.smsCode) {
                    $faPopup.alert({
                        title: '未填写短信验证码'
                    });
                }
                else if(!self.data.confirmPassword){
                    $faPopup.alert({
                        title:'未填写密码'
                    })
                }
                else if (!/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,18}$/.test(self.data.confirmPassword)) {
                    $faPopup.alert({
                        title: '密码格式有误'
                    })
                }
                else if (self.data.confirmPassword.length < 6 || self.data.confirmPassword.length > 18) {
                    $faPopup.alert({
                        title: '密码长度应在6-18位之间'
                    });
                }  else {

                    $faAPI.user.forgetLoginPwd(self.data).then(function (json) {

                        $faPopup.alert({
                            title: '密码重置成功'
                        });

                        self.hide();
                    });
                }
            },
            done: function () {

                var self = this;

                // if (!self.data.mobile || !self.data.verifyCode) {
                //   self.init();
                //   self.step = 1;
                // } else if (!self.data.vCode) {
                //   $faPopup.alert({
                //     title: '未填写短信验证码'
                //   });
                // } else if (!self.data.confirmPassword) {
                //   $faPopup.alert({
                //     title: '未填写重置密码'
                //   });
                // } else
                if (!/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,18}$/.test(self.data.confirmPassword)) {
                    $faPopup.alert({
                        title: '密码格式有误'
                    });
                } else if (self.data.confirmPassword.length < 6 || self.data.confirmPassword.length > 18) {
                    $faPopup.alert({
                        title: '密码长度应在6-18位之间'
                    });
                } else if (self.data.confirmPassword != self.data.confirmPassword2) {
                    $faPopup.alert({
                        title: '两次密码输入不一致！'
                    });
                } else {

                    $faAPI.user.forgetLoginPwd(self.data).then(function (json) {

                        $faPopup.alert({
                            title: '密码重置成功'
                        });

                        self.hide();
                    });
                }
            }
        });

        /**
         * [fastLogin]
         * 快捷登录
         */
        $faModal('fastLogin', 'views/common/fastLogin.html', $rootScope, {
            interval: 90,
            sendTimer: '',
            initialize: function () {
                var self = this;
                self.data = {
                    _pt: 'wap',
                    loginName: $faUser.info.mobile,
                    validatecode: ''
                };

                self.interval = 0;
            },
            sendVcode: function () {
                var self = this;
                var _data = this.data;
                if (!self.data.loginName) {
                    $faPopup.alert({
                        title: '未填写手机号码'
                    });
                } else if (!/^1\d{10}$/.test(self.data.loginName)) {
                    $faPopup.alert({
                        title: ' 手机号码格式错误'
                    });
                } else {
                    self.interval = 90;
                    $faAPI.media.sendLoginVcode({mobile: self.data.loginName}).then(function (resq) {
                        if(resq.AB) {
                            $faPopup.alert({
                                title: '短信请求过于频繁，请稍候再试！'
                            });
                        } else {
                            $interval.cancel(self.sendTimer);

                            self.sendTimer = $interval(function () {
                                if (self.interval > 0) {
                                    self.interval--;
                                } else {
                                    $interval.cancel(self.sendTimer);
                                    self.interval = 0;
                                }
                            }, 1000);
                        }
                    });
                }
            },
            showXieyi: function () {
                $rootScope.modal.showXieyi();
            },
            update: function (json) {
                var self = this;
                $faUser.update();
                $faUtil.cookie('_token') && $faUtil.localStorage('_token', $faUtil.cookie('_token').replace(/\"/g, ''));
                self.hide();
            },
            done: function () {
                var self = this;
                console.log('done');
                if (!self.data.loginName) {
                    $faPopup.alert({
                        title: '请输入手机号码'
                    });
                } else if (!/^1\d{10}$/.test(self.data.loginName)) {
                    $faPopup.alert({
                        title: '手机号码格式错误'
                    });
                } else if (!self.data.validatecode) {
                    $faPopup.alert({
                        title: '请输入手机验证码'
                    });
                } else {
                    $faAPI.user.quickLogin(self.data).then(function (json) {
                        $rootScope.isshowac = true;//显示广告英雄会
                        //console.info("快捷登录："+JSON.stringify(json))
                        self.update(json);
                        $faUtil.cookie('phoneid', json.phoneid, {
                            path: '/',
                            expires: 1296000
                        });
                        $faUtil.cookie('token', json.token, {
                            path: '/',
                            expires: 1296000
                        });
                        //用来更新视频状态
                        //$rootScope.isUserLogin = '1';
                        try {
                            $rootScope.fastLogin.hide();
                            $rootScope.login.hide();
                        } catch (e) {
                        }
                        if (self.mcallback) {
                            console.log(json);
                            self.mcallback(json.loginName)
                        }
                        //2017/10/13 紧急修复，用来保持活动的登录
                        //window.localStorage.setItem("rankPhone", json.loginName);
                        getryToken();
                        //if(!json.flagVistProjectInfo){
                        //  $state.go('app.myself.certification');
                        //}


                    });
                }
            }
        });

        /**
         * 用户认证
         */
        $faModal('startpage', 'views/common/startpage.html', $rootScope, {
            initialize: function() {
                var self = this;
                self.data = {};
            },
            login: function() {
                this.hide();
                $rootScope.modal.login(function () {

                    //登录回调
                    $faUtil.localStorage('user', $faUser.info);
                    $faUser.info.isLogin = true;

                    $state.go('shopHome');

                    window.localStorage.setItem("startpage", "seen");
                });
            },
            zhuce: function() {
                $rootScope.modal.register();
            }
        })

        $ionicPlatform.ready(function () {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                cordova.plugins.Keyboard.disableScroll(true);
            }

            //网络连接
            if(window.cordova && window.cordova.plugins) {
                //网络链接成功
                document.addEventListener('online', function () {
                    console.log('网络连接成功');
                    //if (navigator.connection.type == Connection.WIFI) {
                    //    console.log('已经切换到Wifi网络');
                    //}
                    $rootScope.isNetworkOk = true;
                    $rootScope.$apply();
                }, false);
                //网络断开
                document.addEventListener('offline', function () {
                    console.log('网络已经断开');
                    $rootScope.isNetworkOk = false;

                    var url =$location.path();

                    if(url.indexOf('/network') > -1) {
                        $rootScope.isInPrompt = true;
                    } else {
                        $rootScope.isInPrompt = false;
                    }

                    $rootScope.$apply();
                }, false);
            }

            //用来做一次刷新
            $rootScope.isReload = false;
            //全局保存竞价code
            $rootScope.bidID = {};
            //百度统计
            $rootScope.$on('$stateChangeStart', function () {
                _hmt && _hmt.push(['_trackPageview', $location.path()]);
            });
            //全局唯一返回
            $rootScope.back = function () {
                $ionicHistory.goBack();
            };
            $rootScope.go = function (stateName) {
                $state.go(stateName);
            };

            window.goUrlInfo = $rootScope.goUrlInfo = function (url) {
                //var url= 'http://localhost:4001/#/inform/list/3';
                if (url.indexOf('http') < 0 || url.indexOf('#') < 0) {
                    $faPopup.alert({
                        title: '跳转地址错误'
                    });
                    return
                }
                //console.log(url);
                //$state.go('active.hongbao');
                var count = url.split('/');
                //获取路由
                var last_pos = url.lastIndexOf('/');
                var first_pos = url.indexOf('#');

                try {
                    if ((count.length - 1) > 5) {
                        //路由有参数
                        //获取最后一个参数
                        var param = url.substring(last_pos + 1);
                        _url = url.substring(first_pos + 2, last_pos);
                        _url = _url.replace('/', '.');
                        //console.log(_url);
                        if(_url=='order') {
                            _url = 'app.order';
                        }
                        $state.go(_url, {id: param});
                    } else {
                        _url = url.substring(first_pos + 2);
                        _url = _url.replace('/', '.');
                        //console.log(_url);
                        if(_url=='order') {
                            _url = 'app.order';
                        }
                        $state.go(_url);
                    }
                } catch (err) {
                }
            };

            //ios-资料预览
            window.previewPdf = $rootScope.previewPdf = function (url, name, type, sharePhone) {
                //资料下载阅读埋点
                if(typeof(sharePhone) != 'undefined'){
                    if(!sharePhone) {
                        var reqData = {
                            type: type,
                            host: $location.host(),
                            path: $location.path(),
                            param: $stateParams.id,
                            source: 'WAP',
                            shopId: $faUser.info.mobile

                        };
                        $faAPI.shops.statis({
                            type: 'statisitics',
                            data: reqData
                        }).then(function (json) {
                        });
                    }
                }


                var url_ = reqUrl + url;
                if ($faPlatform.IOSAPP) {
                    prePdf(url_, name);
                } else {

                    var imgurl = 'https://static-superfa-cn.alikunlun.com/upload/bann/20170714/advertImage_1499998278795.jpg';
                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        cordova.exec(null, null, "MyPlugin", "previewPdf", [url_, name, imgurl]);
                    }
                }

            };

            //去往推送消息的页面--需要使用全局变量
            window.goPushPage = function (url) {
                goUrlInfo(url);
            };
            //判断是否安装微信

            document.addEventListener("deviceready", function(){
                Wechat.isInstalled(function (installed) {
                    if(installed) {
                        $rootScope.isWXAppInstall = '1';
                    } else {
                        $rootScope.isWXAppInstall = '0';
                    }
                }, function (reason) {
                    //alert("Failed: " + reason);
                });

                if($rootScope.newIOSAPP) {//ios系统
                    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
                }
            }, false);

            //发送邮件历史记录
            $rootScope.snedMailHistory = [];

            //打开外部活动--还未实现外部活动页面与app中的交互
            $rootScope.windowopen = function (link) {
                //link = 'http://wap5.superfa.cn/#/active/hongbao';
                //alert(link);
                if (link) {
                    var ref = window.open(link, '_blank', 'location=no');
                    ref.addEventListener('loadstart', function (event) {
                        //var url = event.url;
                        //    var count = url.split('/');
                        //    //console.log(count.length-1);
                        //    //获取路由
                        //    var last_pos = url.lastIndexOf('/');
                        //    //console.log(last_pos);
                        //    var first_pos = url.indexOf('#');
                        //    try {
                        //        if((count.length-1)>5){
                        //            //路由有参数
                        //            //获取最后一个参数
                        //            var param = url.substring(last_pos+1);
                        //            _url = url.substring(first_pos+2,last_pos);
                        //            _url = _url.replace('/','.');
                        //            $state.go(_url,{id:param});
                        //        }else {
                        //            _url = url.substring(first_pos+2);
                        //            _url = _url.replace('/','.');
                        //            //console.log(_url)
                        //            //console.log(url)
                        //            $state.go(_url);
                        //        }
                        //    }catch (err){
                        //    }
                    });
                }
            };

            //android app退出
            var backnum = 0;
            $ionicPlatform.registerBackButtonAction(function (event) {
                if (isOpenLogin) {
                    navigator.app.exitApp();
                }
                try {
                    $timeout(function () {
                        backnum = 0
                    }, 800);
                    backnum++;
                    if (backnum == 2) {
                        //var hiht = $ionicPopup.show({
                        //  title:'再按一次退出',
                        //  buttons:[]
                        //});
                        //$timeout(function() {
                        //  hiht.close();
                        //}, 2000);
                        navigator.app.exitApp();
                    }
                    window.history.back();
                    event.preventDefault();
                }

                catch (err) {
                }
            }, 500);


            //清除APP推送圆点
            $rootScope.clearPush = function () {
                if ($faPlatform.IOSAPP||$faPlatform.androidAPP) {
                    //ios方法
                    //PushSign();
                    window.plugins.jPushPlugin.setBadge(0)
                    window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);//清除本地应用角标
                }
            }

            if((!ISWEB && $faUtil.localStorage.get('user') && $faUtil.localStorage.get('user').isLogin) || ISWEB) {
                refUser(getryToken());
            }


            if($rootScope.newIOSAPP || $rootScope.newAndroidAPP) {
                $rootScope.ishavewx = false;
                Wechat.isInstalled(function (installed) {

                    if (!installed) {
                        $rootScope.ishavewx = false
                    } else {
                        $rootScope.ishavewx = true;
                    }
                })
            }


            if ($faPlatform.IOSAPP) {
                //统计用户启动app次数埋点
                var reqData = {
                    type: '110900',
                    host: domainname,
                    path: $location.path(),
                    param: $location.search(),
                    source: 'WAP'
                };
                setTimeout(function(){
                    $faAPI.shops.statis({
                        type: 'statisitics',
                        data: reqData
                    }).then(function (json) {
                    });
                }, 1000)
            }
        });

        //消息 - 融云
        {

            if(ISWEB) {
                $rootScope.goShophomeNews = function () {
                    // $rootScope.isNewsCome = false;

                    $state.go('shopChatList')
                    btnshareShophomeNews()
                }
            } else {

                $rootScope.goShophomeNews = function () {

                    // $rootScope.isNewsCome = false;
                    btnshareShophomeNews()
                    if ($faPlatform.IOSAPP) {
                        mychatlist();
                    } else if ($faPlatform.androidAPP){
                        document.addEventListener("deviceready", OnDeviceReady, false);
                        function OnDeviceReady() {
                            cordova.exec(null, null, "MyPlugin", "mychatlist", []);
                        }
                    }


                }

            }

            //点击消息按钮统计
            function btnshareShophomeNews() {

                var reqData = {
                    type: '110702',
                    host: $location.host(),
                    path: $location.path(),
                    param: $location.search(),
                    source: 'WAP',
                    shopId: $rootScope.shopUserPhone,
                    userId: $faUser.info.mobile

                };
                $faAPI.shops.statis({
                    type: 'statisitics',
                    data: reqData
                }).then(function (json) {
                });
            }

            //融云 - 用户是否还有未读消息
            window.getNewsReadNum = function(noReadNum) {
                if(!noReadNum || noReadNum <= 0) {
                    $rootScope.isNewsCome = false;
                } else {
                    $rootScope.isNewsCome = true;
                }
            }

            // function initRongyun(userInfo) {
            //     if (!userInfo.appKey || !userInfo.token) {
            //         return false;
            //     }
            //
            //     //公有云初始化
            //     RongIMLib.RongIMClient.init(userInfo.appKey);
            //     instance = RongIMClient.getInstance();
            //
            //     //连接状态监听器
            //     RongIMClient.setConnectionStatusListener({
            //         onChanged: function (status) {
            //             switch (status) {
            //                 case RongIMLib.ConnectionStatus.CONNECTED:
            //                     console.log("链接成功 ");
            //                     //callbacks.CONNECTED && callbacks.CONNECTED(instance);
            //                     break;
            //                 case RongIMLib.ConnectionStatus.CONNECTING:
            //                     console.log('正在链接');
            //                     break;
            //                 case RongIMLib.ConnectionStatus.DISCONNECTED:
            //                     console.log('断开连接');
            //                     break;
            //                 case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
            //                     console.log('其他设备登录');
            //                     break;
            //                 case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
            //                     console.log('域名不正确');
            //                     break;
            //                 case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
            //                     console.log('网络不可用');
            //                     break;
            //             }
            //         }
            //     });
            //
            //
            //     RongIMClient.setOnReceiveMessageListener({
            //         // 接收到的消息
            //         onReceived: function (message) {
            //             console.info(message)
            //             if(message.messageDirection=='2') {//接受到对方消息
            //                 $rootScope.isNewsCome = true;
            //             }
            //         }
            //     });
            //     //此接口必须在init()方法之后，连接融云服务器 connect 之前调用。
            //     RongIMClient.getInstance().hasRemoteUnreadMessages(userInfo.token,{
            //         onSuccess:function(hasMessage){
            //             if(hasMessage){
            //                 // 有未读的消息
            //                 console.log('是否有未读消息');
            //                 console.log(hasMessage);
            //                 $rootScope.isNewsCome = true;
            //             }else{
            //                 // 没有未读的消息
            //                 console.log('是否有未读消息');
            //                 console.log(hasMessage);
            //             }
            //         },onError:function(err){
            //             // 错误处理...
            //             console.log('获取未读消息错误');
            //         }
            //     });
            //
            //
            //     //开始链接
            //     RongIMClient.connect(userInfo.token, {
            //         onSuccess: function (id) {
            //         },
            //         onTokenIncorrect: function () {
            //             console.log('token无效');
            //         },
            //         onError: function (errorCode) {
            //             var info = '';
            //             switch (errorCode) {
            //                 case RongIMLib.ErrorCode.TIMEOUT:
            //                     info = '超时';
            //                     break;
            //                 case RongIMLib.ErrorCode.UNKNOWN_ERROR:
            //                     info = '未知错误';
            //                     break;
            //                 case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
            //                     info = '不可接受的协议版本';
            //                     break;
            //                 case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
            //                     info = 'appkey不正确';
            //                     break;
            //                 case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
            //                     info = '服务器不可用';
            //                     break;
            //             }
            //             console.log(info);
            //         }
            //     });
            //
            // }
        }

        function refUser(callback) {
            var user = $rootScope.user = {
                info: {}
            };
            $faAPI.user.info().then(function (json) {
                var _info = {};
                //add-2016/5/6，全局认证状态--nomad-使用全局变量，退出销毁
                //1.未提交认证，2.98认证中，3.99认证失败
                $rootScope.userRole = json.user.uRole;
                $rootScope.userImage = json.user.uImage;

                $rootScope.curUserRole = json.user.uRole;

                if (json.user.uRole == 1 || json.user.uRole == 98 || json.user.uRole == 99) {
                    $rootScope.userRole = 'RZ';
                } else {
                    $rootScope.userRole = 'ZC';
                }
                //if(!json.user.flagVistProjectInfo){
                //  $state.go('app.myself.certification');
                //}


                angular.forEach($faMAP.user, function (value, key) {

                    _info['isLogin'] = true;

                    if (key === 'name') {
                        _info[key] = json.user.uRealName || (json.user.faUserWechatDTO ? json.user.faUserWechatDTO.nickname : undefined) || json.user.uLoginName;
                    } else if (key === "avatar") {
                        _info[key] = (json.user.faUserWechatDTO ? json.user.faUserWechatDTO.headimgurl : undefined) || json.user.uImage;
                    } else if (key === "industry") {
                        _info[key] = json.user.authenticationDTO ? json.user.authenticationDTO.trade : undefined;
                    } else if (key === "working") {
                        _info[key] = json.user.authenticationDTO ? json.user.authenticationDTO.tradeAge : undefined;
                    } else {
                        _info[key] = json.user[value];
                    }

                });

                user.info = $faUtil.extend(user.info, _info);
                $faUtil.localStorage('user', user.info);

                $faUser.info = user.info;//用户信息

                if(typeof callback === "function") {
                    callback();
                }

                setTimeout(function(){
                    $rootScope.$apply();
                }, 1000)
            }, function (json) {

                if (json.statusCode === '2001') {
                    $rootScope.userRole = 'DL';

                    //up-nomad-2016-4-13--zanshi

                    //直接跳转会引发第一次进个人，又退回来。--nomad.2016.04.14
                    //$state.go('app');
                }

            });
        }

        //极光推送
        {
            //当设备就绪时
            var onDeviceReady = function() {
                console.log("JPushPlugin:Device ready!");
                initiateUI();
            };

            //获取RegistrationID
            var getRegistrationID = function() {
                window.plugins.jPushPlugin.getRegistrationID(onGetRegistrationID);
            };

            //注册设备ID
            $rootScope.isJPushRegistrat = "0";
            var onGetRegistrationID = function(data) {
                try {
                    console.log("JPushPlugin:registrationID is " + data);

                    if (data.length == 0) {
                        var t1 = window.setTimeout(getRegistrationID, 1000);
                    }
                    console.info("onGetRegistrationID："+data)

                    //如果用户已登录则将极光推送注册设备ID保存至数据库
                    console.info("注册设备："+$faUser.info.isLogin+"---"+$rootScope.isJPushRegistrat)
                    if($faUser.info.isLogin && $rootScope.isJPushRegistrat=='0') {
                        console.info("==================================执行设备注册==================================")
                        //保存设备ID
                        $faAPI.user.userPhoneAlias({shopAlias: data}).then(function (res) {
                            if(res.statusCode=='0000') {
                                $rootScope.isJPushRegistrat='1';
                            }
                        })
                    }

                } catch (exception) {
                    console.log(exception);
                }
            };

            //设置标签和别名
            var onTagsWithAlias = function(event) {
                console.info("onTagsWithAlias-data"+JSON.stringify(event))
                try {
                    console.log("onTagsWithAlias");
                    var result = "result code:" + event.resultCode + " ";
                    result += "tags:" + event.tags + " ";
                    result += "alias:" + event.alias + " ";
                    console.info("onTagsWithAlias:"+result)
                } catch (exception) {
                    console.log(exception)
                }
            };

            //打开通知的回调函数
            var onOpenNotification = function(event) {
                console.info("onOpenNotification-data:"+JSON.stringify(event))
                try {
                    if (device.platform == "Android") {

                        if(event.extras.msgtype) {
                            if (event.extras.msgtype == '03') {//客户来访
                                $rootScope.isCusvisit = false;
                                $rootScope.$apply();

                                if(event.extras.redirct) {
                                    var base = new Base64();
                                    var url = base.decode(event.extras.redirct);
                                    url = url.split('/#/')[1];

                                    if(url=='order') {
                                        url = 'app.order';
                                        $state.go(url);
                                    } else {
                                        $state.go(url);
                                    }
                                }

                                //window.location.href = url;
                                if ($faPlatform.IOSAPP || $faPlatform.androidAPP) {
                                    //ios方法
                                    //PushSign();
                                    window.plugins.jPushPlugin.setBadge(0);//清除极光推送角标
                                    window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);//清除本地应用角标
                                }
                            } else if (event.extras.msgtype == '06') {//金策师资讯版块
                                if(event.extras.redirct) {
                                    var url = angular.fromJson(event.extras.redirct);
                                    if(url.type=='1') {//1.即时快讯
                                        $state.go('kuaixunDetail', {id: url.id, type: '1'})
                                    } else if(url.type=='2') {//2.资讯简报
                                        $faAPI.shops.detailFpShopInformation({id:url.id}).then(function(jsdata){
                                            $faAPI.shops.countInformation({id:url.id}).then(function(redata){
                                                // $scope.$apply()
                                            })

                                            var d = jsdata.dto;
                                            if (!ISWEB) {
                                                if ($faPlatform.IOSAPP) {
                                                    Briefing('资讯简报', d.articleLink, d.birefDesc, d.hotImg)
                                                }else if ($faPlatform.androidAPP) {
                                                    document.addEventListener("deviceready", OnDeviceReady, false);
                                                    function OnDeviceReady() {
                                                        cordova.exec(null, null, "MyPlugin", "jianbao", ['资讯简报',d.birefDesc,d.hotImg,d.articleLink]);
                                                    }
                                                }
                                            }
                                        })
                                    } else if(url.type=='3') {//3.热点资讯
                                        $state.go('redianDetail', {id: url.id, type: '3'})
                                    } else if(url.type=='4') {//4.早鸟理财师驿站
                                        $state.go('zaoNiaoDetail',{id: url.id, type: '4'})
                                    }
                                }
                            }

                        } else {//融云消息
                            // $rootScope.isNewsCome = false;

                            if ($faPlatform.IOSAPP) {
                                mychatlist();
                            } else if ($faPlatform.androidAPP){
                                document.addEventListener("deviceready", OnDeviceReady, false);
                                function OnDeviceReady() {
                                    cordova.exec(null, null, "MyPlugin", "mychatlist", []);
                                }
                            }
                        }
                    } else {

                        //判断消息类型
                        if(event.msgtype) {
                            if (event.msgtype == '03') {//客户来访
                                $rootScope.isCusvisit = false;
                                $rootScope.$apply();

                                if(event.redirct) {
                                    var base = new Base64();
                                    var url = base.decode(event.redirct);
                                    url = url.split('/#/')[1];

                                    if(url=='order') {
                                        url = 'app.order';
                                        $state.go(url);
                                    } else {
                                        $state.go(url);
                                    }
                                }

                                //window.location.href = url;
                                if ($faPlatform.IOSAPP || $faPlatform.androidAPP) {
                                    //ios方法
                                    //PushSign();
                                    window.plugins.jPushPlugin.setBadge(0);//清除极光推送角标
                                    window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);//清除本地应用角标
                                }

                                //$state.go('visitorList')
                            } else if (event.msgtype == '06') {//金策师资讯版块
                                if(event.redirct) {
                                    var url = angular.fromJson(event.redirct);
                                    if(url.type=='1') {//1.即时快讯
                                        $state.go('kuaixunDetail', {id: url.id, type: '1'})
                                    } else if(url.type=='2') {//2.资讯简报
                                        $faAPI.shops.detailFpShopInformation({id:url.id}).then(function(jsdata){
                                            $faAPI.shops.countInformation({id:url.id}).then(function(redata){
                                                // $scope.$apply()
                                            })

                                            var d = jsdata.dto;
                                            if (!ISWEB) {
                                                if ($faPlatform.IOSAPP) {
                                                    Briefing('资讯简报', d.articleLink, d.birefDesc, d.hotImg)
                                                }else if ($faPlatform.androidAPP) {
                                                    document.addEventListener("deviceready", OnDeviceReady, false);
                                                    function OnDeviceReady() {
                                                        cordova.exec(null, null, "MyPlugin", "jianbao", ['资讯简报',d.birefDesc,d.hotImg,d.articleLink]);
                                                    }
                                                }
                                            }
                                        })
                                    } else if(url.type=='3') {//3.热点资讯
                                        $state.go('redianDetail', {id: url.id, type: '3'})
                                    } else if(url.type=='4') {//4.早鸟理财师驿站
                                        $state.go('zaoNiaoDetail',{id:url.id,type:'4'})
                                    }
                                }
                            }
                        } else {//融云消息
                            // $rootScope.isNewsCome = false;

                            if ($faPlatform.IOSAPP) {
                                mychatlist();
                            } else if ($faPlatform.androidAPP){
                                document.addEventListener("deviceready", OnDeviceReady, false);
                                function OnDeviceReady() {
                                    cordova.exec(null, null, "MyPlugin", "mychatlist", []);
                                }
                            }
                        }
                    }
                } catch (exception) {
                    console.log("JPushPlugin:onOpenNotification" + exception);
                }
            };

            //接收到通知时的回调函数
            var onReceiveNotification = function(event) {
                console.info("onReceiveNotification-data:"+JSON.stringify(event))
                console.info("环境："+device.platform +"=="+event.msgtype)
                console.info(event.msgtype=='03')
                try {
                    $rootScope.isHaveShopnews = true;

                    var alertContent;
                    if (device.platform == "Android") {
                        //alertContent = event.alert;

                        //判断消息类型
                        if(event.extras.msgtype=='04') {//04:理财师身份认证审核通知
                            refUser();
                        }
                        else if(event.extras.msgtype=='03') {//客户来访
                            $rootScope.isCusvisit = true;
                            $rootScope.$apply();
                        }
                    } else {
                        alertContent = event.aps.alert;

                        //判断消息类型
                        if(event.msgtype=='04') {//04:理财师身份认证审核通知
                            refUser();
                        }
                        else if(event.msgtype=='03') {//客户来访
                            $rootScope.isCusvisit = true;
                            $rootScope.$apply();
                            console.info("客户来访："+$rootScope.isCusvisit)
                        }
                    }
                    console.info("onReceiveNotification:"+alertContent);
                } catch (exception) {
                    console.log(exception)
                }
            };

            //接收到消息时的回调函数
            var onReceiveMessage = function(event) {
                console.info("onReceiveMessage-data:"+JSON.stringify(event))
                console.info("环境："+device.platform )
                try {
                    var message;
                    if (device.platform == "Android") {
                        message = event.message;
                    } else {
                        message = event.content;
                    }
                    console.info("onReceiveMessage:"+message)
                } catch (exception) {
                    console.log("JPushPlugin:onReceiveMessage-->" + exception);
                }
            };

            //初始化jpush
            var initiateUI = function() {
                try {
                    window.plugins.jPushPlugin.init();
                    window.setTimeout(getRegistrationID, 1000);
                    if (device.platform != "Android") {
                        window.plugins.jPushPlugin.setDebugModeFromIos();
                        window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
                    } else {
                        window.plugins.jPushPlugin.setDebugMode(true);
                        window.plugins.jPushPlugin.setStatisticsOpen(true);
                    }
                } catch (exception) {
                    console.log(exception);
                }
            };

            document.addEventListener("jpush.setTagsWithAlias", onTagsWithAlias, false);
            document.addEventListener("deviceready", onDeviceReady, false);
            document.addEventListener("jpush.openNotification", onOpenNotification, false);
            document.addEventListener("jpush.receiveNotification", onReceiveNotification, false);
            document.addEventListener("jpush.receiveMessage", onReceiveMessage, false);
        }

        //手机从后台切到前台
        document.addEventListener("resume", function() {
            if($faUser.info && $faUser.info.isLogin) {
                refUser();

                $rootScope.ddzt = {};
                $faAPI.inform.ddtz().then(function(json){
                    $rootScope.ddzt = json;
                    //if(json.jPushShopCount !=undefined && json.jPushShopCount!='' && json.jPushShopCount!=null) {
                    if(parseInt(json.jPushShopCount)>0) {
                        $rootScope.isHaveShopnews = true;
                    } else {
                        $rootScope.isHaveShopnews = false;
                    }
                    //}
                });
            }

            if($faPlatform.IOSAPP||$faPlatform.androidAPP) {
                window.plugins.jPushPlugin.getRegistrationID(onGetRegistrationID);
            }


            if ($faPlatform.IOSAPP) {
                //统计用户启动app次数埋点
                var reqData = {
                    type: '110900',
                    host: reqUrl.substr(7),
                    path: $location.path(),
                    param: $location.search(),
                    source: 'WAP'
                };
                $faAPI.shops.statis({
                    type: 'statisitics',
                    data: reqData
                }).then(function (json) {
                });
            }

        }, false);

        var str = '{"id": "1", "type":"2"}';
        var t = angular.fromJson(str);
        console.info(t);
    })
    .config(function ($httpProvider) {
        //http请求拦截器
        $httpProvider.interceptors.push(function () {
            return {
                request: function (config) {
                    try {
                        config.headers.phoneid = getCookie('phoneid');
                        config.headers.token = getCookie('token');

                    } catch (e) {
                        //  //alert(e)
                    }

                    return config
                },
                response: function (response) {
                    //console.log(response.config);
                    var url = response.config.url;
                    if (url.indexOf('logout') >= 0) {
                        setCookie('phoneid', '');
                        setCookie('token', '');
                        return response
                    }

                    return response
                }
            }
        });

    })
    .config(function ($stateProvider, $locationProvider, $urlRouterProvider, $ionicConfigProvider) {
        // ionic相关配置
        //最大缓存模板--不能设置其为0，否则tab切换会销毁view。默认10
        $ionicConfigProvider.views.maxCache();

        //预读模板数--调试时可设置为0，默认30
        $ionicConfigProvider.templates.maxPrefetch(0);
        //设置返回按钮的文字。
        $ionicConfigProvider.backButton.text('');
        //设置返回按钮的图标。
        $ionicConfigProvider.backButton.icon('');
        //设置是否将上一个view视图的title设置成返回按钮的文字，iOS是默认的true。
        $ionicConfigProvider.backButton.previousTitleText(false);
        //设置视图之间的过渡切换效果，默认是platform
        $ionicConfigProvider.views.transition('none');
        $ionicConfigProvider.platform.android.navBar.alignTitle('center');
        $ionicConfigProvider.tabs.position('bottom');
        $ionicConfigProvider.tabs.style('standard');
        //禁止侧滑后退事件，暂时没研究后退做什么处理，目前会导致页面空白，默认为true
        $ionicConfigProvider.views.swipeBackEnabled(false);
        //</ion-scroll>在谷歌浏览器上调试时发现安卓手机上滚动条失效，但是在iOS上正常，结果发现无论怎么调整都是无效，花了好多时间。
        //后来在一个网页上看到这样的解释：
        //ionic 1.2 开始使用 原生 scroll 来取代原来的JavaScript scroll, 不过这个有可能造成原来的infinite scroll工作不正常，解决办法是在 config里加上
        //ios 使用原生scroll,android 使用js scroll---是否区分
        $ionicConfigProvider.scrolling.jsScrolling(true);


        // Ionic uses AngularUI Router which uses the concept of states
        // Learn more here: https://github.com/angular-ui/ui-router
        // Set up the various states which the app can be in.
        // Each state's controller can be found in controllers.js
        $stateProvider

            .state('app', {
                url: '/?inviteId',
                cache: false,
                templateUrl: 'views/common/startpage.html' + version,
                controller: 'MainCtrl',
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.sletype = null;

                    $rootScope.isshownet = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;

                    $rootScope.isshownet = true;
                }

            })

            .state('app.tradePassword', {
                cache: false,
                url: 'tradePassword',
                views: {
                    '@': {
                        templateUrl: 'views/wallet/setTradePassword.html' + version,
                        controller: 'myselfSetTradePasswordCtrl'
                    }
                }
            })

            .state('super.cjzx', {
                url: '/cjzx/{id:[0-9a-z\-]{0,50}}',
                views: {
                    '@': {
                        templateUrl: 'views/newsinfo/super.cjzx.html' + version,
                        controller: 'cjzxCtrl',
                        resolve: {
                            cjzx: function ($stateParams, $faAPI) {
                                return $faAPI.inform.zxggDetail({
                                    newId: $stateParams.id
                                });
                            }
                        }
                    }
                }
            })
            .state('super.zxxw', {
                url: '/zxxw/{id:[0-9a-z\-]{0,50}}',
                views: {
                    '@': {
                        templateUrl: 'views/newsinfo/super.zxxw.html' + version,
                        controller: 'zxxwCtrl',
                        resolve: {
                            zxxw: function ($stateParams, $faAPI) {
                                return $faAPI.inform.zxxw({
                                    id: $stateParams.id
                                });
                            }
                        }
                    }
                }
            })
            .state('super.cpxx', {
                url: '/cpxx/{id:[0-9a-z\-]{0,50}}',
                views: {
                    '@': {
                        templateUrl: 'views/newsinfo/super.cpxx.html' + version,
                        controller: 'cpxxCtrl',
                        resolve: {
                            cpxx: function ($stateParams, $faUser, $faAPI) {
                                return $faAPI.inform.cpxx_dytz_info({
                                    id: $stateParams.id
                                });
                            }
                        }
                    }
                }
            })
            .state('inform', {
                url: '/inform',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/newsinfo/inform.html' + version,
                        controller: 'informCtrl'
                    }
                },
                onEnter: function ($rootScope,$ionicSideMenuDelegate) {
                    $rootScope.isHide = false;
                    $ionicSideMenuDelegate.toggleLeft(false);
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;

                }
            })
            .state('inform.jytz', {
                url: '/jytz/{id:[0-9a-z\-]{0,50}}',
                views: {
                    '@': {
                        templateUrl: 'views/newsinfo/inform.jytz.html' + version,
                        controller: 'jytzCtrl',
                        resolve: {
                            jytz: function ($stateParams, $faAPI) {
                                return $faAPI.inform.jytz({
                                    id: $stateParams.id
                                });
                            }
                        }
                    }
                }
            })
            .state('inform.zxgg', {
                url: '/zxgg/{id:[0-9a-z\-]{0,50}}',
                views: {
                    '@': {
                        templateUrl: 'views/newsinfo/inform.zxgg.html' + version,
                        controller: 'zxggCtrl',
                        resolve: {
                            zxgg: function ($stateParams, $faAPI) {
                                return $faAPI.inform.zxggDetail({
                                    newId: $stateParams.id
                                });
                            }
                        }
                    }
                }
            })
            .state('inform.dytz', {
                url: '/dytz/{id:[0-9a-z\-]{0,50}}',
                views: {
                    '@': {
                        templateUrl: 'views/newsinfo/inform.dytz.html' + version,
                        controller: 'dytzCtrl',
                        resolve: {
                            dytz: function ($stateParams, $faUser, $faAPI) {
                                return $faAPI.inform.cpxx_dytz_info({
                                    id: $stateParams.id
                                });
                            }
                        }
                    }
                }
            })
            .state('inform.set', {
                url: '/set',
                views: {
                    '@': {
                        templateUrl: 'views/newsinfo/inform.set.html' + version,
                        controller: 'informSetCtrl'
                    }
                }
            })
            .state('inform.list', {
                url: '/list/{id:[0-9a-z\-]{0,50}}',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/newsinfo/list.html' + version,
                        controller: 'informlistCtrl'
                    }
                }
            })

            .state('app.download', {
                cache: false,
                url: '/d',
                templateUrl: 'views/common/download.html' + version,
                controller: 'DownloadCtrl'
            })

            .state('tools', {
                url: '/tools',
                views: {
                    '@': {
                        templateUrl: 'views/common/tools.html' + version,
                        controller: function ($scope, $state, $faUser, $rootScope) {
                            $scope.goDetails = function (url) {
                                $faUser.info.isLogin ? $state.go(url) : $rootScope.modal.login();
                            }
                        }
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = true;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                }
            })

            .state('search', {
                url: '/search?typelist',
                cache: true,
                views: {
                    '@': {
                        templateUrl: 'views/common/wap3Search.html' + version,
                        controller: 'wap3SearchCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;

                }
            })


            .state('invite', {
                url: '/inviteHome?phone&userimg&name',
                views: {
                    '@': {
                        templateUrl: 'views/invite/inviteHome.html' + version,
                        controller: 'inviteHomeCtrl'
                    }
                }
            })
            .state('inside', {
                url: '/inside',
                views: {
                    '@': {
                        templateUrl: 'views/invite/inside.html' + version,
                        controller: 'insideCtrl'
                    }
                }
            })
            .state('kcList', {
                cache: 'false',
                url: '/keList/:soldOut',
                views: {
                    '@': {
                        templateUrl: 'views/myCourse/kcList.html' + version,
                        controller: 'CourseListCtrl'
                    }
                }
            })
            .state('kcDetail', {
                cache: 'false',
                url: '/kcDetail/:id/:type',
                views: {
                    '@': {
                        templateUrl: 'views/myCourse/kcDetail.html' + version,
                        controller: 'CourseDetailCtrl'
                    }
                }
            })
            .state('drainList', {
                url: '/drainList?id',
                views: {
                    '@': {
                        templateUrl: 'views/drain/drain_list.html' + version,
                        controller: 'drainListCtrl'
                    }
                }
            })

            .state('shoPreview', {
                url: '/shoPreview?sphone&ismaster',
                //cache:false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/preview/shoPreview.html' + version,
                        controller: 'shoPreviewCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('shopHome', {
                url: '/shopHome?sphone&ismaster',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/shopHome.html' + version,
                        controller: 'shoPreviewCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isActive1 = true;
                    $rootScope.isActive2 = false;
                    $rootScope.isActive3 = false;
                    $rootScope.isActive4 = false;
                    $rootScope.isActive5 = false;

                    $rootScope.isNeedBotbar = '0';//0:灰色 1：重置 2：白色
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                    $rootScope.isNeedBotbar = '1';

                }
            })
            .state('shopPreview', {
                url: '/shopPreview?sphone&ismaster&isFromZixun',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/shopPreview.html' + version,
                        controller: 'shopIndexCtrl'
                    }
                },
                onEnter: function ($rootScope) {

                    $rootScope.isHide = false;

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('shopperinfo', {
                url: 'shops/shopperinfo',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/shopPerInfo.html' + version,
                        controller: 'shopPerInfoCtrl'
                    }
                },
                onEnter: function ($rootScope,$ionicSideMenuDelegate) {
                    $rootScope.isHide = false;
                    $ionicSideMenuDelegate.toggleLeft(false)
                },
                onExit: function ($rootScope,$ionicSideMenuDelegate) {
                    $rootScope.isHide = false;
                    $ionicSideMenuDelegate.toggleLeft(false)
                }
            })
            .state('shopChat', {
                url: '/shopChat?tid&ismaster&proid&protype&prosource&sphone',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/shopchat_index.html' + version,
                        controller: 'shopChatCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('app.upload', {
                url: 'upload?id&pName',
                views: {
                    '@': {
                        templateUrl: 'views/shops/proupload.html' + version,
                        controller: 'userUploadCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;

                }
            })
            .state('app.uploadOk', {
                cache: false,
                url: 'uploadOk',
                views: {
                    '@': {
                        templateUrl: 'views/shops/uploadOk.html' + version,
                        controller: function($scope, $state){
                            $scope.toIndex = function(){
                                $state.go('app.shopsProduct2',{isuploadok:true});

                            }
                        }
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;

                }
            })

            .state('shopChatList', {
                url: '/shopChatList',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/shopchat_list.html' + version,
                        controller: 'shopChatListCtrl'
                    }
                },
                onEnter: function ($rootScope) {



                    $rootScope.isHide = true;
                    $rootScope.isActive1 = false;
                    $rootScope.isActive2 = false;
                    $rootScope.isActive3 = true;
                    $rootScope.isActive4 = false;
                    $rootScope.isActive5 = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            //数据统计路由
            .state('shopTransaction', {
                url: '/shopTransaction',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/dataStatistics/transaction.html' + version,
                        controller: 'TransactionCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isActive1 = false;
                    $rootScope.isActive2 = false;
                    $rootScope.isActive3 = false;
                    $rootScope.isActive4 = true;
                    $rootScope.isActive5 = false;

                    $rootScope.isNeedBotbar = '2';
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                    $rootScope.isNeedBotbar = '1';
                }
            })

            .state('shopDataProduct', {
                url: '/shopDataProduct',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/dataStatistics/dataProduct.html' + version,
                        controller: 'DataProductCtr'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '1';

                }
            })


            .state('shopDataFlow', {
                url: '/shopDataFlow',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/dataStatistics/dataFlow.html' + version,
                        controller: 'DataFlowCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '1';

                }
            })
            //2018/4/25  数据汇总
            .state('dataSummary', {
                url: '/dataSummary',
                //cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/data/summaryHome.html' + version,
                        controller: 'dataSummaryCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '1';

                }
            })
            .state('transverse', {
                url: '/transverse?phone&time&oid',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/data/transverse.html' + version,
                        controller: 'transverseCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '1';

                }
            })
            .state('shopSaySay', {
                url: '/shopSaySay?sphone',
                views: {
                    '@': {
                        templateUrl: 'views/shops/preview/saysay.html' + version,
                        controller: 'shopSaySayCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('previewProduct', {
                url: '/previewProduct?sphone&uid',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/preview/productList.html' + version,
                        controller: 'previewListCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('visitorList', {
                url: '/visitorList',
                // cache:false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/visitor/list.html' + version,
                        controller: 'visitorListCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = true;
                    $rootScope.isActive1 = false;
                    $rootScope.isActive2 = true;
                    $rootScope.isActive3 = false;
                    $rootScope.isActive4 = false;
                    $rootScope.isActive5 = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('addClient', {
                url: '/addClient?weixinAppid',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/visitor/addClient.html' + version,
                        controller: 'addClientCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('visitorDetail', {
                url: '/visitorDetail?weixinAppid',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/visitor/visitorView.html' + version,
                        controller: 'visitorDetailCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('clientDetail', {
                url: '/clientDetail?id',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/visitor/detail.html' + version,
                        controller: 'clientDetailCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('subscribe', {
                url: '/subscribe',
                //cache:false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/subscribe/list.html' + version,
                        controller: 'subscribeCtrl'
                    }
                },
                //resolve: {
                //  product : function ($faAPI) {
                //    return $faAPI.shops.clientOrder();
                //  }
                //},
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('product.clientOrder', {
                url: '/clientOrder/?productId&productType&productName&sphone&self',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/subscribe/clientOrder.html' + version,
                        controller: 'clientOrderCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;

                }
            })

            .state('app.shopsIndex', {
                cache: false,
                url: 'shops/index',
                views: {
                    '@': {
                        templateUrl: 'views/shops/index.html' + version,
                        controller: 'shopsIndexCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;
                }
            })
            .state('app.shopsdimenCode',{
                cache:false,
                url:'shops/dimenCode',
                views:{
                    '@':{
                        templateUrl:'views/shops/dimenCode.html'+version,
                        controller: 'DimenCodeCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '1';
                }
            })
            .state('app.shopsProduct', {
                cache: false,
                url: 'shops/product',
                views: {
                    '@': {
                        templateUrl: 'views/shops/product.html' + version,
                        controller: 'shopsProductCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                }
            })
            .state('app.shopsProduct2', {
                url: 'shops/product2?sphone&isuploadok&isonmsg',
                views: {
                    '@': {
                        templateUrl: 'views/shops/product2.html' + version,
                        controller: 'shopsProductCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;

                    $rootScope.isNeedBotbar = '0';
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isExitProAdd = false;

                    $rootScope.isNeedBotbar = '1';
                }
            })
            .state('productEdit', {
                cache: false,
                url: '/productEdit?id&type',
                views: {
                    '@': {
                        templateUrl: 'views/shops/productEdit.html' + version,
                        controller: 'productEdittCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                }
            })
            .state('myProduct2Detail', {
                cache: false,
                url: '/myProduct2Detail?id&share&sharePhone&isshare&issm',
                views: {
                    '@': {
                        templateUrl: 'views/shops/myProduct2Detail.html' + version,
                        controller: 'myProduct2DetailCtrl'
                    }
                },
                resolve: {
                    product: function ($stateParams, $faAPI) {
                        return $faAPI.product.detailFpShopUserRelProduct({
                            id: $stateParams.id
                        });
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '1';
                }
            })
            .state('proAddMore', {
                cache: false,
                url: '/proAddMore?id',
                views: {
                    '@': {
                        templateUrl: 'views/shops/proAddMore.html' + version,
                        controller: 'proAddMoreCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                }
            })
            .state('app.shopsProductAdd', {
                url: 'shops/productAdd?msgid',
                //cache:false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/productAdd.html' + version,
                        controller: 'shopsProductAddCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isExitProAdd = true;
                }
            })
            .state('app.shopsDataHome', {
                url: 'shops/dataHome?sphone&shre',
                views: {
                    '@': {
                        templateUrl: 'views/shops/data/dataHome.html' + version,
                        controller: 'shopsDataHomeCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;
                }
            })
            .state('app.shopsDataList', {
                url: 'shops/dataList',
                views: {
                    '@': {
                        templateUrl: 'views/shops/data/dataList.html' + version,
                        controller: 'shopsDataListCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;
                }
            })
            .state('app.shopsDataDetails', {
                url: 'shops/dataDetails?type&param',
                views: {
                    '@': {
                        templateUrl: 'views/shops/data/dataDetails.html' + version,
                        controller: 'shopsDataDetailCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;
                }
            })
            .state('app.shopsAcList', {
                url: 'shops/aclist?sphone',
                cache:false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/activity/shopAclist.html' + version,
                        controller: 'shopsAcListCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.navShow = true;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;
                }
            })
            .state('app.shopsAcDetail', {
                url: 'shops/AcDetail/:id?sphone',
                views: {
                    '@': {
                        templateUrl: 'views/shops/activity/shopAcDetail.html' + version,
                        controller: 'shopsAcDetailCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';//0:灰色 1：重置 2：白色
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;
                    $rootScope.isNeedBotbar = '1';
                }
            })
            .state('app.shopscheckPerson', {
                url: 'shops/checkPerson/:id',
                views: {
                    '@': {
                        templateUrl: 'views/shops/activity/checkApplyPerson.html' + version,
                        controller: 'shopsCheckApplyCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;
                }
            })
            .state('app.previewShopsAcList', {
                url: 'shops/previewAcList/:sphone',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/activity/shopPreviewAclist.html' + version,
                        controller: 'shopsPreviewAcListCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;
                }
            })
            .state('app.shopsPreviewAcDetail', {
                url: 'shops/previewAcDetail/:sphone/:id',
                views: {
                    '@': {
                        templateUrl: 'views/shops/activity/shopPreviewAcDetail.html' + version,
                        controller: 'shopsPreviewAcDetailCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;
                }
            })

            .state('addblogs', {
                url: 'blogs',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/blogs/add.html' + version,
                        controller: 'blogsAddCtrl'
                    }
                }
            })
            .state('blogslist', {
                url: 'shops/blogslist?sphone',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/blogs/list.html' + version,
                        controller: 'blogsListCtrl'
                    }
                }
            })

            .state('product', {
                url: '/product',
                abstract: true
            })

            .state('product.shopxtzgdetail', {
                url: '/shopxtzgdetail/{id:[0-9a-z\-]{0,50}}?share&sharePhone',
                //cache:false,
                views: {
                    '@':{
                        templateUrl: 'views/shops/preview/wap4_xtzgDetail.html' + version,
                        controller: 'ProductxtzgDetailCtrl'
                    }
                },
                resolve: {
                    product: function ($stateParams, $faAPI) {
                        return $faAPI.product.detail({
                            code: $stateParams.id
                        });
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                    $rootScope.isNeedBotbar = '1';
                }
            })
            .state('product.xtzgOrder', {
                url: '/xtzgOrder/?pid&type&name',
                cache:false,
                views:{
                    '@':{
                        templateUrl: 'views/product/wap4_xtzgOrder.html' + version,
                        controller: 'xtzgOrderCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;

                }
            })
            .state('product.xtzgdetail', {
                url: '/xtzgdetail/{id:[0-9a-z\-]{0,50}}?share&sharePhone&issm',
                cache:false,
                views: {
                    '@':{
                        templateUrl: 'views/product/wap4_xtzgDetail.html' + version,
                        controller: 'ProductxtzgDetailCtrl'
                    }
                },
                resolve: {
                    product: function ($stateParams, $faAPI) {
                        return $faAPI.product.detail({
                            code: $stateParams.id
                        });
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;

                }
            })
            .state('product.simu', {
                url: '/simu/{id:[0-9a-z\-]{0,50}}?share&sharePhone&onlypro&issm',
                cache:false,
                views:{
                    '@':{
                        //templateUrl: 'views/product/simuDetail.html' + version,
                        templateUrl: 'views/product/wap4_simuDetail.html' + version,
                        controller: 'ProductSimuCtrl'
                    }
                },
                resolve: {
                    product: function($stateParams, $faAPI) {
                        return $faAPI.product.simuDetail({
                            id: $stateParams.id
                        });
                    },
                    checkStatus: function($faAPI) {
                        return $faAPI.user.status();
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                    $rootScope.isNeedBotbar = '1';
                }
            })

            .state('product.pevc', {
                url: '/pevc/{id:[0-9a-z\-]{0,50}}?share&sharePhone&issm',
                cache:false,
                views: {
                    '@':{
                        templateUrl: 'views/product/wap4_pevcDetail.html' + version,
                        controller: 'ProductPevcDetailCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;

                }
            })

            .state('product.shoppevc', {
                url: '/shoppevc/{id:[0-9a-z\-]{0,50}}?share&sharePhone',

                //cache:false,
                views: {
                    '@':{
                        templateUrl: 'views/shops/preview/wap4_pevcDetail.html' + version,
                        controller: 'ProductPevcDetailCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                    $rootScope.isNeedBotbar = '2';
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                    $rootScope.isNeedBotbar = '1';
                }
            })
            .state('contrastIndex',{
                url:'/contrastIndex',
                cache:false,
                views:{
                    '@':{
                        templateUrl: 'views/product/contrast/contrast_index.html' + version,
                        controller: 'contrastIndexCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })

            //活动管理
            .state('active',{
                url: '/active',
                abstract: true,
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })
            .state('active.movie',{
                url:'/movie',
                views:{
                    '@':{
                        templateUrl: 'views/activity/activity-movie.html' + version,
                        controller: 'activeMovieCtrl'
                    }
                }
            })
            .state('active.hongbao',{
                url:'/hongbao',
                views:{
                    '@':{
                        templateUrl: 'views/activity/hongbao.html' + version,
                        controller: 'activeHongbaoCtrl'
                    }
                }
            })
            .state('active.50rmb',{
                url:'/50rmb',
                views:{
                    '@':{
                        templateUrl: 'views/activity/50rmb.html' + version,
                        controller: 'active50rmbCtrl'
                    }
                }
            })
            .state('active.explain',{
                url:'/explain',
                views:{
                    '@':{
                        templateUrl: 'views/activity/explain.html' + version
                        // controller: 'activeHongbaoCtrl'
                    }
                }
            })
            //注册
            .state('zhuce', {
                url: '/zhuce',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/common/register.html' + version,
                        controller: 'register'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;

                }
            })

            //订单
            .state('app.order', {
                cache: false,
                url: 'order?statusStage',
                views: {
                    '@': {
                        templateUrl: 'views/order/index.html' + version,
                        controller: 'orderIndexCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = true;
                    $rootScope.isActive1 = false;
                    $rootScope.isActive2 = false;
                    $rootScope.isActive3 = false;
                    $rootScope.isActive4 = false;
                    $rootScope.isActive5 = true;

                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = false;

                }
            })
            .state('myBankList', {
                url: 'myBankList?goid',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/myself/wap4_myBankList.html' + version,
                        controller: 'myBankListCtrl'
                    }
                },
                onEnter: function ($ionicSideMenuDelegate,$rootScope) {
                    $ionicSideMenuDelegate.toggleLeft(false);
                    $rootScope.isHide = false;

                }
            })
            .state('banklist', {
                url: '/banklist?goid&payM',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/pay/bindBankCard.html' + version,
                        controller: 'bankCardListCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;

                }
            })

            .state('rankIndex', {
                cache: false,
                url: '/rankIndex',
                views: {
                    '@': {
                        templateUrl: 'views/rankname/homepage.html' + version,
                        controller: 'rankIndexCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;

                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;

                }
            })
            .state('eggrank', {
                cache: false,
                url: '/eggrank',
                views: {
                    '@': {
                        templateUrl: 'views/rankname/eggrank.html' + version,
                        controller: 'eggrankCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;

                }
            })

            .state('fastLogin', {
                //cache: false,
                url: '/fastLogin?backurl',
                views: {
                    '@': {
                        templateUrl: 'views/common/acFastLogin.html' + version,
                        controller: 'FastLoginCtrl'
                    }
                }
            })
            .state('darenxiu', {
                //cache: false,
                url: '/darenxiu',
                views: {
                    '@': {
                        templateUrl: 'views/common/darenxiu.html' + version,
                        controller: 'rankIndexCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;

                }
            })

        //    网络连接失败
            .state('promptlink', {
                url: 'network',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/prompt.html' + version,
                        controller: 'promptCtrl'
                    }
                }
            })
            //帮助与反馈
            .state('HelpLink', {
                url: 'Help',
                cache: false,
                views: {
                    '@': {
                        templateUrl: 'views/shops/help/Help.html' + version,
                        controller: 'HelpLink'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isNeedBotbar = '2';
                },
                onExit: function($rootScope) {
                    $rootScope.isNeedBotbar = '1';
                }
            })

            //引导页
            .state('Bootpage',{
                url:'Bootpage?initIndex',
                cache:false,
                views:{
                    '@': {
                        templateUrl: 'views/shops/boot/Bootpage.html' + version,
                        controller: 'bootCtrl'
                    }
                }
            })
            //答题页
            .state('customer',{
                url:'/customer?phone',
                views:{
                    '@': {
                        templateUrl: 'views/customer/add.html' + version,
                        controller: 'customerCtrl'
                    }
                },
                onEnter: function ($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function ($rootScope) {
                    $rootScope.isHide = true;
                }
            })

            .state('shopPictures',{
                url:'shopPictures',
                cache:false,
                views:{
                    '@': {
                        templateUrl: 'views/shops/shopPictures.html' + version,
                        controller:'shopPicturesCtr'
                    }
                }
            })

            .state('prodQRcode',{
                url:'/prodQRcode?proid&protype&phone',
                cache:false,
                views:{
                    '@': {
                        templateUrl: 'views/shops/proqrcode.html' + version,
                        controller:'prodQRcodeCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })


            //金策师资讯
            .state('information',{
                url:'/shops/information?sphone',
                cache:true,
                views:{
                    '@': {
                        templateUrl: 'views/shops/Information/information.html' + version,
                        controller:'InformationCtr'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })


            //即时快讯
            .state('newFlashList',{
                url:'/shops/newFlashList?sphone',
                cache:false,
                views:{
                    '@': {
                        templateUrl: 'views/shops/Information/newFlashList.html' + version,
                        controller:'newFlashListCtr'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })

            //英雄帖活动 - 答题认证
            .state('yxtAuth',{
                url:'/yxtAuth',
                views:{
                    '@': {
                        templateUrl: 'views/ac/yxtac/yxtAuth.html' + version,
                        controller: 'customerCtrl'
                    }
                }
            })

            //资讯简报
            .state('jianbaoDetail',{
                url:'/infromationBriefingDetail/:id/:type?sphone',
                views:{
                    '@': {
                        templateUrl: 'views/modals/Briefing.html' + version,
                        controller: 'InformationDetailCtrl'
                    }
                }
            })
        //热点资讯
            .state('redianDetail',{
                url:'/infromationHotspotDetail/:id/:type?sphone',
                //cache:false,//添加完产品，回来需要刷新数据
                views:{
                    '@': {
                        templateUrl: 'views/shops/Information/HotspotDetail.html' + version,
                        controller: 'InformationDetailCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })
        //快讯
            .state('kuaixunDetail',{
                url:'/infromationNewListDetail/:id/:type?sphone',
                views:{
                    '@': {
                        templateUrl: 'views/modals/newListDetail.html' + version,
                        controller: 'InformationDetailCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })

        //早鸟理财师驿站
            .state('zaoNiaoDetail',{
                url:'/infromationEarlyBirdDetail/:id/:type?sphone',
                views:{
                    '@': {
                        templateUrl: 'views/modals/EarlyBird.html' + version,
                        controller: 'InformationDetailCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })
            //微信建群信息填写
            .state('statisticsInfo',{
                url:'/statisticsInfo',
                cache: false,
                views:{
                    '@': {
                        templateUrl: 'views/statistics/statisticsInfo.html' + version,
                        controller: 'statisticsInfoCtrl'
                    }
                }
            })
            .state('dataMechHome',{
                url:'/dataMechHome?productName&param&id&name&tabTime',
                views:{
                    '@': {
                        templateUrl: 'views/shops/dataMech/dataHome.html' + version,
                        controller: 'datamechHomeCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })



            .state('dataOrderDetails',{
                url:'/dataOrderDetails?amountType&id&name&tabTime',
                views:{
                    '@': {
                        templateUrl: 'views/shops/dataMech/dataOrderDetails.html' + version,
                        controller: 'dataOrderDetailsCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })


            .state('dataProductlist',{
                url:'/dataProductlist?param&type&productName&id&name&tabTime',
                views:{
                    '@': {
                        templateUrl: 'views/shops/dataMech/dataProductlist.html' + version,
                        controller: 'dataProductlistCtrl'
                    }
                },
                onEnter: function($rootScope) {
                    $rootScope.isHide = false;
                },
                onExit: function($rootScope) {
                    $rootScope.isHide = true;
                }
            })
        // Each tab has its own nav history stack:

        // if none of the above states are matched, use this as the fallback
        $urlRouterProvider.otherwise('/');

    })
